package head.first.model.observer;

import java.util.ArrayList;

/**
 * create by yiyongyao
 * Date:2018/3/6 下午4:18
 * Description: 主题实现类
 */
public class WetherData implements Subject {

    private volatile static ArrayList observers;

    private float temp;

    private float humidity;

    private float pressure;

    public WetherData() {

        if(null==observers)
        {
            synchronized (WetherData.class)
            {
                if(null==observers)
                {
                    observers = new ArrayList();
                }
            }

        }
    }


    @Override
    public void registerObserver(Observer o) {
        observers.add(o);
    }

    @Override
    public void removeObserver(Observer o) {
        int i = observers.indexOf(o);
        if (i > 0) {
            observers.remove(i);
        }
    }

    @Override
    public void notifyObservers() {

        System.out.println("观察者的数量:"+observers.size());

        for (int i = 0; i < observers.size(); i++) {
            Observer observer = (Observer) observers.get(i);
            observer.update(temp, humidity, pressure);
        }

    }

    /**
     * 数据改变时调用
     */
    public void measurementsChanged() {
        notifyObservers();
    }

    /**
     * 数据初始化,相当于气象站
     *
     * @param temp
     * @param humidity
     * @param pressure
     */
    public void setMeasurements(float temp, float humidity, float pressure) {
        this.temp = temp;
        this.humidity = humidity;
        this.pressure = pressure;
    }

}
